﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenSoftStore.BusinessLogic.Admin;
using OpenSoftStore.BusinessLogic.Common;
using OpenSoftStore.BusinessLogic.Money;
using OpenSoftStore.BusinessLogic.Provider;
using OpenSoftStore.Client.Common;
using OpenSoftStore.Orm.Model;
using OpenSoftStore.Orm.View;

namespace OpenSoftStore.Client.UIL.ManageMoney
{
    public partial class MoneyList : UserControl
    {
        private static MoneyList instance;

        private MoneyLogic LgcMoney;

        public AdminLogic LgcAdmin;
        /// <summary>
        /// 返回一个该控件的实例。如果之前该控件已经被创建，直接返回已创建的控件。
        /// 此处采用单键模式对控件实例进行缓存，避免因界面切换重复创建和销毁对象。
        /// </summary>
        public static MoneyList Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new MoneyList();
                }
                //BindDataGrid(); // 每次返回该控件的实例前，都将对DataGridView控件的数据源进行重新绑定。
                return instance;
            }
        }

        public TreeLogic LgcTree;

        /// <summary>
        /// 私有的控件实例化方法，创建实例只能通过该控件的Instance属性实现。
        /// </summary>
        private MoneyList()
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;
            LgcMoney = new MoneyLogic();
            LgcTree = new TreeLogic();
            LgcAdmin = new AdminLogic();
            SetUi();//加载类型树
            GetMoney();//加载收支流水单
            GetAccount();//加载账户信息
            GetSumMoney();//收支统计
            SPACommon.SetDataGridStyle(dgvAccount);
            SPACommon.SetDataGridStyle(DgvGrid);
            SPACommon.SetDataGridStyle(DgvMoneySum);
            SPACommon.ShowSummary(DgvMoneySum);
            SPACommon.ShowSummary(DgvGrid);
            SPACommon.ShowSummary(dgvAccount);

            var shops = LgcAdmin.GetShops();
            cmbShop.DataSource = shops;
            cmbShop.DisplayMember = "Name";
            cmbShop.ValueMember = "Id";

            cmbShopTotal.DataSource = shops;
            cmbShopTotal.DisplayMember = "Name";
            cmbShopTotal.ValueMember = "Id";

            btnTree_Add.Visible = SysPowerManager.IsHavePower(SysPowerManager.管理收支分类);
            btnTree_Update.Visible = SysPowerManager.IsHavePower(SysPowerManager.管理收支分类);
            btnTree_Delete.Visible = SysPowerManager.IsHavePower(SysPowerManager.管理收支分类);

            tlMoneyAdd.Visible = SysPowerManager.IsHavePower(SysPowerManager.添加收支);
            tlUpdataMoney.Visible = SysPowerManager.IsHavePower(SysPowerManager.修改收支);
            tlMoneyDelete.Visible = SysPowerManager.IsHavePower(SysPowerManager.删除收支);
			//SysPowerManager.IsHavePower(SysPowerManager.查看收支统计);
			//SysPowerManager.IsHavePower(SysPowerManager.查看账户相关信息);
        }


        private void MoneyList_Load(object sender, EventArgs e)
        {
            dtFrom.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
            dtTo.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59");

            dtTotalFrom.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
            dtTotalTo.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59");
        }

        #region 加载列表
        private void SetUi()
        {
            trTree.Refresh();
            LgcTree.SetTreeNode(LgcTree.GetMoneyTree(), trTree);
            trTree.ExpandAll();
            trTree.SelectedNode = trTree.Nodes[0];
            SPACommon.SetTreeStyle(trTree);
        }

        private void GetMoney()
        {
            string where =string.Format("where T_Money.AddTime between #{0}# and #{1}# and T_Money.ShopId ='{2}' and T_Tree.Code like '{3}%' " +
                                        "Order by T_Money.AddTime desc", dtFrom.Value, dtTo.Value, cmbShop.SelectedValue, trTree.SelectedNode.Tag);
            DgvGrid.AutoGenerateColumns = false;
            var moneyData = LgcMoney.GetMoneyDataTable(where);
            DgvGrid.DataSource = moneyData;
            lblMoneyCount.Text = DgvGrid.RowCount.ToString();
        }
        private void GetSumMoney()
        {
            //收支流水账
            if (dgvAccount != null)
            {
                DgvMoneySum.AutoGenerateColumns = false;
                string strwhere = "and AddTime between #" + dtTotalFrom.Value + "#and#" + dtTotalTo.Value + "#";
                var datatable = LgcMoney.GetMoneySumNamber(strwhere);
                DgvMoneySum.DataSource = datatable;
                lblCount.Text = DgvMoneySum.RowCount.ToString();
            }
        }
        public void GetAccount()
        {
            //账户
            if (dgvAccount != null)
            {
                var name = txtName.Text;
                dgvAccount.AutoGenerateColumns = false;
                dgvAccount.DataSource = LgcMoney.GetAccountDataTable(" where T_Account.Name like '%" + name + "%' Order by T_Account.AddTime desc");
                lblAccountCount.Text = dgvAccount.RowCount.ToString();
            }
        }
        #endregion


        private void toolStripLabel1_Click(object sender, EventArgs e)
        {
            var moenyAddWindow = new MoenyAddWindow();
            moenyAddWindow.Show();
        }

        private void toolStripLabel2_Click(object sender, EventArgs e)
        {
            if (DgvGrid.CurrentRow == null) return;
            var moenyAddWindow = new MoenyAddWindow();
            var id = DgvGrid.CurrentRow.Cells["Id"].Value.ToString();
            moenyAddWindow.GetMoney(id);
            moenyAddWindow.Show();
        }

        private void btAddItem_Click(object sender, EventArgs e)
        {
        }

        private void btUpdateItme_Click(object sender, EventArgs e)
        {
            if (trTree.SelectedNode == null) return;
            trTree.LabelEdit = true;
            trTree.SelectedNode.BeginEdit();
        }

        private void btDeleteItme_Click(object sender, EventArgs e)
        {
            LgcTree.Delete(trTree);
        }

        private void trTree_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (trTree.SelectedNode == null) return;
            trTree.SelectedNode.EndEdit(true);
            LgcTree.SaveTreeNode(trTree, sender, e, "Money");
        }



        private void toolStripLabel3_Click_1(object sender, EventArgs e)
        {
            //MessageBox.Show("不允许删除此类型支付单"); //return null;
            if (MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK) return;
            if (DgvGrid.CurrentRow == null) return;
            var id = DgvGrid.CurrentRow.Cells["Id"].Value.ToString();
            var pro = new T_Money() { Id = id };
            var provider = new MoneyLogic();
            provider.DeleteMoney(pro);
            GetMoney();
        }

        /// <summary>
        /// 修改账户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tlUpdataAccount_Click(object sender, EventArgs e)
        {
            if (dgvAccount.CurrentRow == null) return;
            var addAcountwindow = new AddAccountWindow();
            var id = dgvAccount.CurrentRow.Cells["dataGridViewTextBoxColumn12"].Value.ToString();
            addAcountwindow.GetAccount(id);
            addAcountwindow.Show();
        }

        private void AddAccount_Click(object sender, EventArgs e)
        {
            var addAcountwindow = new AddAccountWindow();
            addAcountwindow.Show();
        }

        private void btSearch_Click(object sender, EventArgs e)
        {
            GetAccount();
        }

        private void btSeach_Click(object sender, EventArgs e)
        {
            GetSumMoney();
        }

        private void tlDeleteAccount_Click(object sender, EventArgs e)
        {

            if (MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK) return;
            if (dgvAccount.CurrentRow == null) return;
            var id = dgvAccount.CurrentRow.Cells["dataGridViewTextBoxColumn12"].Value.ToString();
            var pro = new T_Account { Id = id };
            var provider = new MoneyLogic();
            provider.DeleteAccount(pro);
            GetAccount();
        }

        public void button1_Click_1(object sender, EventArgs e)
        {
            GetMoney();
        }

        private void btnTree_Add_Click(object sender, EventArgs e)
        {

            if (trTree.SelectedNode == null) return;
            trTree.LabelEdit = true;

            var treeNode = new TreeNode { Text = "新子项" };
            TreeNode tnParent = trTree.SelectedNode;
            tnParent.Nodes.Add(treeNode);
            trTree.SelectedNode = treeNode;
            treeNode.BeginEdit();
        }

        private void btnTree_Update_Click(object sender, EventArgs e)
        {
            if (!LgcTree.CanUpdateMoneyTree(trTree)) return;
            if (trTree.SelectedNode == null) return;
            trTree.LabelEdit = true;
            trTree.SelectedNode.BeginEdit();
        }

        private void btnTree_Delete_Click(object sender, EventArgs e)
        {
            LgcTree.DeleteMoneyTree(trTree);
        }

        private void trTree_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }

        private void trTree_AfterSelect_1(object sender, TreeViewEventArgs e)
        {
            GetMoney();
            //if (trTree.SelectedNode.Tag == null) return;
            //DgvGrid.DataSource = null;
            //string where = " where T_Tree.Code like '" + trTree.SelectedNode.Tag.ToString() + "%' Order by AddTime desc";
            //var moneyData = provider.GetMoneyView(where);
            //DgvGrid.DataSource = moneyData;
        }

        private void btnSearch_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button1_Click_1(null, null);
            }
        }

        private void glassButton1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                GetMoney();
            }
        }

        private void glassButton2_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                GetAccount();
            }
        }

        private void DgvGrid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {

        }

        private void DgvGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            toolStripLabel2_Click(null, null);
        }

        private void dgvAccount_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            tlUpdataAccount_Click(null, null);
        }

    }
}
